<template>
  <div class="quick-actions-panel">
    <!-- 浮动操作按钮 -->
    <transition name="fab-scale">
      <div v-show="!isExpanded" class="fab-button" @click="togglePanel">
        <el-icon class="fab-icon" :class="{ rotating: isExpanded }">
          <MagicStick />
        </el-icon>
      </div>
    </transition>

    <!-- 快捷面板 -->
    <transition name="panel-slide">
      <div v-show="isExpanded" class="actions-panel">
        <div class="panel-header">
          <h3>
            <el-icon><Tools /></el-icon>
            快捷操作
          </h3>
          <el-button text @click="togglePanel">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="panel-content">
          <!-- 常用功能 -->
          <div class="section">
            <div class="section-title">常用功能</div>
            <div class="action-grid">
              <div
                v-for="action in commonActions"
                :key="action.id"
                class="action-item"
                @click="handleAction(action)"
              >
                <div class="action-icon" :style="{ background: action.color }">
                  <el-icon :size="24">
                    <component :is="action.icon" />
                  </el-icon>
                </div>
                <div class="action-label">{{ action.label }}</div>
                <div v-if="action.shortcut" class="action-shortcut">{{ action.shortcut }}</div>
              </div>
            </div>
          </div>

          <!-- 最近使用 -->
          <div class="section">
            <div class="section-title">
              最近使用
              <el-button text size="small" @click="clearHistory">清空</el-button>
            </div>
            <div v-if="recentActions.length > 0" class="recent-list">
              <div
                v-for="(item, index) in recentActions"
                :key="index"
                class="recent-item"
                @click="handleRecentAction(item)"
              >
                <el-icon><Clock /></el-icon>
                <span class="recent-name">{{ item.name }}</span>
                <span class="recent-time">{{ formatTime(item.time) }}</span>
              </div>
            </div>
            <el-empty v-else description="暂无最近操作" :image-size="60" />
          </div>

          <!-- 快速创建 -->
          <div class="section">
            <div class="section-title">快速创建</div>
            <el-button-group class="create-buttons">
              <el-button type="primary" @click="quickCreate('crud')">
                <el-icon><Grid /></el-icon>
                CRUD页面
              </el-button>
              <el-button type="success" @click="quickCreate('form')">
                <el-icon><Edit /></el-icon>
                表单
              </el-button>
              <el-button type="warning" @click="quickCreate('flow')">
                <el-icon><Share /></el-icon>
                流程
              </el-button>
            </el-button-group>
          </div>

          <!-- AI助手 -->
          <div class="section ai-section">
            <div class="ai-input-wrapper">
              <el-input
                v-model="aiInput"
                placeholder="告诉AI你想创建什么..."
                @keyup.enter="handleAICreate"
              >
                <template #prefix>
                  <el-icon><MagicStick /></el-icon>
                </template>
                <template #suffix>
                  <el-button
                    text
                    :loading="aiLoading"
                    @click="handleAICreate"
                  >
                    <el-icon><Promotion /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
        </div>

        <div class="panel-footer">
          <el-button text @click="showSettings">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
          <el-button text @click="showKeyboardShortcuts">
            <el-icon><Notebook /></el-icon>
            快捷键
          </el-button>
        </div>
      </div>
    </transition>

    <!-- 快捷键提示 -->
    <el-dialog
      v-model="shortcutsVisible"
      title="键盘快捷键"
      width="600px"
    >
      <el-table :data="shortcuts" :show-header="false">
        <el-table-column prop="label" width="200" />
        <el-table-column prop="keys">
          <template #default="{ row }">
            <el-tag v-for="key in row.keys" :key="key" size="small" style="margin-right: 4px">
              {{ key }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  MagicStick,
  Tools,
  Close,
  Clock,
  Grid,
  Edit,
  Share,
  Promotion,
  Setting,
  Notebook,
  Document,
  Connection,
  Cpu,
  ShoppingBag,
  FolderOpened
} from '@element-plus/icons-vue'

const router = useRouter()

const isExpanded = ref(false)
const aiInput = ref('')
const aiLoading = ref(false)
const shortcutsVisible = ref(false)
const recentActions = ref([])

// 常用操作
const commonActions = ref([
  {
    id: 'form-designer',
    label: '表单设计器',
    icon: 'Edit',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    path: '/lowcode/form-designer',
    shortcut: 'Ctrl+F'
  },
  {
    id: 'page-designer',
    label: '页面设计器',
    icon: 'Document',
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    path: '/lowcode/page-designer',
    shortcut: 'Ctrl+P'
  },
  {
    id: 'api-designer',
    label: 'API设计器',
    icon: 'Connection',
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    path: '/lowcode/api-designer',
    shortcut: 'Ctrl+A'
  },
  {
    id: 'code-generator',
    label: '代码生成器',
    icon: 'Cpu',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    path: '/lowcode/code-generator',
    shortcut: 'Ctrl+G'
  },
  {
    id: 'component-market',
    label: '组件市场',
    icon: 'ShoppingBag',
    color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    path: '/lowcode/component-market',
    shortcut: 'Ctrl+M'
  },
  {
    id: 'template-market',
    label: '模板广场',
    icon: 'FolderOpened',
    color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    path: '/lowcode/template-market',
    shortcut: 'Ctrl+T'
  }
])

// 快捷键配置
const shortcuts = ref([
  { label: '打开快捷面板', keys: ['Ctrl', 'K'] },
  { label: '表单设计器', keys: ['Ctrl', 'F'] },
  { label: '页面设计器', keys: ['Ctrl', 'P'] },
  { label: 'API设计器', keys: ['Ctrl', 'A'] },
  { label: '代码生成器', keys: ['Ctrl', 'G'] },
  { label: '组件市场', keys: ['Ctrl', 'M'] },
  { label: '模板广场', keys: ['Ctrl', 'T'] },
  { label: '保存', keys: ['Ctrl', 'S'] },
  { label: '撤销', keys: ['Ctrl', 'Z'] },
  { label: '重做', keys: ['Ctrl', 'Shift', 'Z'] },
  { label: 'AI助手', keys: ['Ctrl', 'Space'] },
  { label: '快速搜索', keys: ['Ctrl', '/', ''] }
])

// 切换面板
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

// 处理操作
const handleAction = (action) => {
  // 记录最近使用
  addToRecent(action.label, action.path)
  
  // 跳转页面
  if (action.path) {
    router.push(action.path)
  }
  
  // 关闭面板
  isExpanded.value = false
}

// 处理最近操作
const handleRecentAction = (item) => {
  if (item.path) {
    router.push(item.path)
    isExpanded.value = false
  }
}

// 快速创建
const quickCreate = (type) => {
  const routes = {
    crud: '/lowcode/quick-builder?type=crud',
    form: '/lowcode/form-designer?mode=create',
    flow: '/lowcode/flow-designer?mode=create'
  }
  
  if (routes[type]) {
    router.push(routes[type])
    isExpanded.value = false
  }
}

// AI创建
const handleAICreate = async () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入你的需求')
    return
  }
  
  aiLoading.value = true
  
  // 模拟AI处理
  setTimeout(() => {
    aiLoading.value = false
    router.push(`/lowcode/ai-assistant?prompt=${encodeURIComponent(aiInput.value)}`)
    isExpanded.value = false
    aiInput.value = ''
  }, 800)
}

// 添加到最近使用
const addToRecent = (name, path) => {
  const recent = {
    name,
    path,
    time: new Date().getTime()
  }
  
  // 避免重复
  const index = recentActions.value.findIndex(item => item.path === path)
  if (index > -1) {
    recentActions.value.splice(index, 1)
  }
  
  recentActions.value.unshift(recent)
  
  // 最多保留10条
  if (recentActions.value.length > 10) {
    recentActions.value.pop()
  }
  
  // 保存到本地
  localStorage.setItem('lowcode_recent_actions', JSON.stringify(recentActions.value))
}

// 清空历史
const clearHistory = () => {
  recentActions.value = []
  localStorage.removeItem('lowcode_recent_actions')
  ElMessage.success('已清空最近使用记录')
}

// 格式化时间
const formatTime = (timestamp) => {
  const now = new Date().getTime()
  const diff = now - timestamp
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return `${Math.floor(diff / 86400000)}天前`
}

// 显示设置
const showSettings = () => {
  ElMessage.info('设置功能开发中...')
}

// 显示快捷键
const showKeyboardShortcuts = () => {
  shortcutsVisible.value = true
}

// 键盘快捷键处理
const handleKeyboard = (e) => {
  // Ctrl+K 打开面板
  if (e.ctrlKey && e.key === 'k') {
    e.preventDefault()
    togglePanel()
  }
  
  // 其他快捷键
  if (e.ctrlKey && !e.shiftKey) {
    const action = commonActions.value.find(a => {
      const key = a.shortcut?.split('+')[1]?.toLowerCase()
      return key === e.key.toLowerCase()
    })
    
    if (action) {
      e.preventDefault()
      handleAction(action)
    }
  }
  
  // ESC 关闭面板
  if (e.key === 'Escape' && isExpanded.value) {
    isExpanded.value = false
  }
}

// 加载最近使用
const loadRecentActions = () => {
  const saved = localStorage.getItem('lowcode_recent_actions')
  if (saved) {
    try {
      recentActions.value = JSON.parse(saved)
    } catch (e) {
      console.error('Failed to parse recent actions:', e)
    }
  }
}

onMounted(() => {
  loadRecentActions()
  window.addEventListener('keydown', handleKeyboard)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyboard)
})
</script>

<style scoped>
.quick-actions-panel {
  position: relative;
}

/* 浮动按钮 */
.fab-button {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1000;
}

.fab-button:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 30px rgba(102, 126, 234, 0.6);
}

.fab-icon {
  color: white;
  font-size: 28px;
  transition: transform 0.3s;
}

.fab-icon.rotating {
  transform: rotate(180deg);
}

/* 操作面板 */
.actions-panel {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 400px;
  max-height: 80vh;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 1001;
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
}

.panel-footer {
  display: flex;
  justify-content: space-around;
  padding: 12px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 分组 */
.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 操作网格 */
.action-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.action-item:hover {
  background: #f5f7fa;
  transform: translateY(-2px);
}

.action-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  color: white;
}

.action-label {
  font-size: 13px;
  color: #303133;
  text-align: center;
  margin-bottom: 4px;
}

.action-shortcut {
  font-size: 11px;
  color: #909399;
  padding: 2px 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

/* 最近使用 */
.recent-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.recent-item:hover {
  background: #f5f7fa;
}

.recent-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.recent-time {
  font-size: 12px;
  color: #909399;
}

/* 快速创建按钮 */
.create-buttons {
  display: flex;
  width: 100%;
}

.create-buttons .el-button {
  flex: 1;
}

/* AI助手区域 */
.ai-section {
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 0;
}

.ai-input-wrapper {
  width: 100%;
}

/* 动画 */
.fab-scale-enter-active,
.fab-scale-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fab-scale-enter-from,
.fab-scale-leave-to {
  transform: scale(0);
  opacity: 0;
}

.panel-slide-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.panel-slide-leave-active {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.panel-slide-enter-from {
  transform: translateY(20px);
  opacity: 0;
}

.panel-slide-leave-to {
  transform: translateY(10px);
  opacity: 0;
}

/* 滚动条样式 */
.panel-content::-webkit-scrollbar {
  width: 6px;
}

.panel-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

